<template>
  <section class="inventory-search-bar art-custom-card">
    <ElForm
      ref="searchFormRef"
      :model="searchForm"
      :label-position="'left'"
      label-width="90px"
    >
      <!-- 维度选择 -->
      <ElRow class="mb-4">
        <ElCol :span="24">
          <ElFormItem label="查询维度" prop="queryType">
            <ElRadioGroup
              v-model="searchForm.queryType"
              size="default"
              @change="handleQueryTypeChange"
            >
              <ElRadioButton label="warehouse">仓库库区</ElRadioButton>
              <ElRadioButton label="item">商品</ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <!-- 搜索表单 -->
      <ElRow class="search-form-row" :gutter="20">
        <!-- 仓库选择 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="仓库" prop="warehouseId">
            <ElSelect
              v-model="searchForm.warehouseId"
              placeholder="请选择仓库"
              filterable
              clearable
              @change="handleWarehouseChange"
            >
              <ElOption
                v-for="warehouse in warehouseList"
                :key="warehouse.id"
                :label="warehouse.warehouseName"
                :value="warehouse.id"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 库区选择 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="库区" prop="areaId">
            <ElSelect
              v-model="searchForm.areaId"
              placeholder="请选择库区"
              :disabled="!searchForm.warehouseId"
              filterable
              clearable
            >
              <ElOption
                v-for="area in filteredAreaList"
                :key="area.id"
                :label="area.areaName"
                :value="area.id"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 商品名称 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="商品名称" prop="itemName">
            <ElInput
              v-model="searchForm.itemName"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </ElFormItem>
        </ElCol>

        <!-- 商品编号 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="商品编号" prop="itemCode">
            <ElInput
              v-model="searchForm.itemCode"
              placeholder="请输入商品编号"
              clearable
              @keyup.enter="handleSearch"
            />
          </ElFormItem>
        </ElCol>

        <!-- 规格名称 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="规格名称" prop="skuName">
            <ElInput
              v-model="searchForm.skuName"
              placeholder="请输入规格名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </ElFormItem>
        </ElCol>

        <!-- 规格编号 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="规格编号" prop="skuCode">
            <ElInput
              v-model="searchForm.skuCode"
              placeholder="请输入规格编号"
              clearable
              @keyup.enter="handleSearch"
            />
          </ElFormItem>
        </ElCol>

        <!-- 批号 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="批号" prop="batchNo">
            <ElInput
              v-model="searchForm.batchNo"
              placeholder="请输入批号"
              clearable
              @keyup.enter="handleSearch"
            />
          </ElFormItem>
        </ElCol>

        <!-- 过期时间 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="过期" prop="daysToExpires">
            <ElSelect
              v-model="searchForm.daysToExpires"
              placeholder="选择过期时间"
              clearable
            >
              <ElOption label="30天内" :value="30" />
              <ElOption label="60天内" :value="60" />
              <ElOption label="90天内" :value="90" />
              <ElOption label="120天内" :value="120" />
              <ElOption label="180天内" :value="180" />
              <ElOption label="365天内" :value="365" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 入库日期 -->
        <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <ElFormItem label="入库日期" prop="createTimeRange">
            <ElDatePicker
              v-model="searchForm.createTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
            />
          </ElFormItem>
        </ElCol>

        <!-- 操作按钮 -->
        <ElCol
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24"
          class="action-column"
        >
          <div class="action-buttons-wrapper">
            <ElButton @click="handleReset" v-ripple>
              <ElIcon><Refresh /></ElIcon>
              重置
            </ElButton>
            <ElButton type="primary" @click="handleSearch" v-ripple>
              <ElIcon><Search /></ElIcon>
              搜索
            </ElButton>
          </div>
        </ElCol>
      </ElRow>
    </ElForm>
  </section>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";

// 定义接口
interface InventoryDetailSearchForm {
  queryType: "warehouse" | "item";
  pageNum: number;
  pageSize: number;
  warehouseId?: number;
  areaId?: number;
  itemName?: string;
  itemCode?: string;
  skuName?: string;
  skuCode?: string;
  batchNo?: string;
  daysToExpires?: number;
  createTimeRange?: string[];
}

interface WarehouseItem {
  id: number;
  warehouseName: string;
}

interface AreaItem {
  id: number;
  areaName: string;
  warehouseId: number;
}

// 定义props和emits
interface Props {
  filter?: Partial<InventoryDetailSearchForm>;
  warehouseList?: WarehouseItem[];
  areaList?: AreaItem[];
}

interface Emits {
  (e: "update:filter", value: InventoryDetailSearchForm): void;
  (e: "search", value: InventoryDetailSearchForm): void;
  (e: "reset"): void;
  (e: "query-type-change", type: "warehouse" | "item"): void;
}

const props = withDefaults(defineProps<Props>(), {
  filter: () => ({
    queryType: "warehouse",
    pageNum: 1,
    pageSize: 10,
  }),
  warehouseList: () => [],
  areaList: () => [],
});

const emit = defineEmits<Emits>();

// 表单引用
const searchFormRef = ref();

// 默认时间
const defaultTime = reactive([
  new Date(0, 0, 0, 0, 0, 0),
  new Date(0, 0, 0, 23, 59, 59),
]);

// 搜索表单
const searchForm = reactive<InventoryDetailSearchForm>({
  queryType: "warehouse",
  pageNum: 1,
  pageSize: 10,
  warehouseId: undefined,
  areaId: undefined,
  itemName: undefined,
  itemCode: undefined,
  skuName: undefined,
  skuCode: undefined,
  batchNo: undefined,
  daysToExpires: undefined,
  createTimeRange: undefined,
});

// 计算属性
const filteredAreaList = computed(() => {
  if (!searchForm.warehouseId || !props.areaList) return [];
  return props.areaList.filter(
    (area) => area.warehouseId === searchForm.warehouseId,
  );
});

/**
 * 监听外部filter变化
 */
watch(
  () => props.filter,
  (newFilter) => {
    if (newFilter) {
      Object.assign(searchForm, {
        queryType: "warehouse",
        pageNum: 1,
        pageSize: 10,
        ...newFilter,
      });
    }
  },
  { immediate: true, deep: true },
);

/**
 * 仓库变化处理
 */
const handleWarehouseChange = (): void => {
  searchForm.areaId = undefined;
};

/**
 * 查询维度变化处理
 */
const handleQueryTypeChange = (type: "warehouse" | "item"): void => {
  // 重置部分表单数据
  if (type === "warehouse") {
    searchForm.areaId = undefined;
  }

  searchForm.pageNum = 1;
  emit("query-type-change", type);
  handleSearch();
};

/**
 * 搜索处理
 */
const handleSearch = (): void => {
  searchForm.pageNum = 1;

  // 同步到父组件
  emit("update:filter", { ...searchForm });
  emit("search", { ...searchForm });
};

/**
 * 重置处理
 */
const handleReset = (): void => {
  searchFormRef.value?.resetFields();

  // 重置表单数据
  Object.assign(searchForm, {
    queryType: "warehouse",
    pageNum: 1,
    pageSize: 10,
    warehouseId: undefined,
    areaId: undefined,
    itemName: undefined,
    itemCode: undefined,
    skuName: undefined,
    skuCode: undefined,
    batchNo: undefined,
    daysToExpires: undefined,
    createTimeRange: undefined,
  });

  // 通知父组件
  emit("update:filter", { ...searchForm });
  emit("reset");
};

// 暴露方法
defineExpose({
  handleSearch,
  handleReset,
});
</script>

<style lang="scss" scoped>
.inventory-search-bar {
  margin-bottom: 16px;
  padding: 24px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);

  .search-form-row {
    :deep(.el-form-item) {
      margin-bottom: 16px;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }

  .action-column {
    .action-buttons-wrapper {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      gap: 12px;
      padding-top: 4px;

      .el-button {
        display: flex;
        align-items: center;
        gap: 6px;
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    padding: 16px;

    .action-column .action-buttons-wrapper {
      justify-content: center;
      margin-top: 8px;
    }
  }
}

// art-custom-card 样式
.art-custom-card {
  border: 1px solid var(--el-border-color-light);
  transition: all 0.3s ease;

  &:hover {
    border-color: var(--el-color-primary-light-5);
    box-shadow: var(--el-box-shadow);
  }
}
</style>
